package grimbo.goodwinfooty.server;

import grimbo.goodwinfooty.service.model.FootyMatrix;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Blob;

public class JDODatastoreDB implements GoodwinFootyDB {
	private static final String CNAME = JDODatastoreDB.class.getName();
	private static final Logger log = Logger.getLogger(CNAME);

	private PersistenceManagerFactory persistenceManagerFactory;

	@Override
	public FootyMatrix loadFootyMatrix() {
		final String MNAME = "loadFootyMatrix()";
		final boolean DEBUG = log.isLoggable(Level.FINE);
		log.entering(CNAME, MNAME);

		PersistenceManager pm = persistenceManagerFactory
				.getPersistenceManager();

		FootyMatrix result = null;

		try {
			Query query = pm.newQuery(MyData.class);
			List list = (List) query.execute();
			if (list.isEmpty()) {
				return null;
			}
			log.info("" + list.size());
			for (int i = 0; i < list.size(); i++) {
				log.info(i + ", " + list.get(i));
			}
			MyData data = (MyData) list.get(list.size() - 1);
			if ((null == data) || (null == data.getData())) {
				return null;
			}
			result = (FootyMatrix) ByteUtils.bytesToObject(data.getData()
					.getBytes());
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}

		log.exiting(CNAME, MNAME);

		return result;
	}

	@Override
	public void saveFootyMatrix(FootyMatrix footyMatrix) {
		final String MNAME = "saveFootyMatrix(FootyMatrix)";
		final boolean DEBUG = log.isLoggable(Level.FINE);
		log.entering(CNAME, MNAME);

		PersistenceManager pm = persistenceManagerFactory
				.getPersistenceManager();

		try {
			MyData data = new MyData();
			data.setData(new Blob(ByteUtils.objectToBytes(footyMatrix)));
			pm.makePersistent(data);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}

		log.exiting(CNAME, MNAME);
	}

	public PersistenceManagerFactory getPersistenceManagerFactory() {
		return persistenceManagerFactory;
	}

	public void setPersistenceManagerFactory(
			PersistenceManagerFactory persistenceManagerFactory) {
		this.persistenceManagerFactory = persistenceManagerFactory;
	}
}
